package cn.haohaowo.controller;

import cn.haohaowo.common.Constants;
import cn.haohaowo.common.SessionContainer;
import cn.haohaowo.entity.Account;
import cn.haohaowo.entity.Book;
import cn.haohaowo.entity.Order;
import cn.haohaowo.entity.ShoppingCart;
import cn.haohaowo.service.BookBizService;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Controller
@RequestMapping("/cart")
public class CartController {

	private static final long serialVersionUID = -3783693513607158879L;

	private Integer id;
	private Integer quantity;
	private String deliveryType;
	
	private String subtotal;
	private String saved;
	private String total;
	private String freight;
	
	private Order preparedOrder;

    private Book book;

    private ShoppingCart shoppingCart;

    private Account account;

	private SessionContainer sessionContainer;
	
	@Autowired
	private BookBizService bookBizService;
	
	public String show(){
		return Constants.SHOW;
	}

    @RequestMapping("/list.do")
	public String addBook(HttpServletRequest request, HttpServletResponse response, int bookId) {
		if(null == quantity || quantity < 1) {
			quantity = 1;
		}

        HttpSession session = request.getSession();
        book = bookBizService.getBook(bookId);
        if (null == book) {
			sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
            shoppingCart = sessionContainer.getShoppingCart();
            shoppingCart.addBook(book, quantity);
			sessionContainer.setShoppingCart(shoppingCart);
			session.setAttribute(Constants.SESSION_CONTAINER_KEY, sessionContainer);
        }

		return Constants.CART;
	}

	@RequestMapping("/removeBook.do")
	public String removeBook(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
		sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
		shoppingCart = sessionContainer.getShoppingCart();
		shoppingCart.removeBook(id);
		sessionContainer.setShoppingCart(shoppingCart);
		session.setAttribute(Constants.SESSION_CONTAINER_KEY, sessionContainer);
		return Constants.CART;
	}

	@RequestMapping("/clearBook.do")
	public String clearBook(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
		sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
		shoppingCart = sessionContainer.getShoppingCart();
		shoppingCart.clear();
		sessionContainer.setShoppingCart(shoppingCart);
		session.setAttribute(Constants.SESSION_CONTAINER_KEY, sessionContainer);

		return Constants.CART;
	}

	@RequestMapping("/confirm.do")
	public String confirm(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
		sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
		shoppingCart = sessionContainer.getShoppingCart();
		preparedOrder = (Order) session.getAttribute(Constants.PREPARED_ORDER_KEY);
		if(null == preparedOrder || shoppingCart.isEmpty()){
			return Constants.SHOW;
		}
		return Constants.CONFIRM;
	}

	@RequestMapping("/updateQuantity.do")
	public String updateQuantity(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
		sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
		shoppingCart = sessionContainer.getShoppingCart();
        book = bookBizService.getBook(id);
        if (null == book &&  null != shoppingCart.getCartItem(id)) {
			shoppingCart.updateQuantity(book, quantity);
			sessionContainer.setShoppingCart(shoppingCart);
			session.setAttribute(Constants.SESSION_CONTAINER_KEY, sessionContainer);

			subtotal = shoppingCart.getCartItem(id).getTotalPrice().toString();
			saved = shoppingCart.getTotalSaved().toString();
			total = shoppingCart.getTotalPrice().toString();
		}
		return Constants.UPDATE_QUANTITY;
	}

	@RequestMapping("/checkout.do")
	public String checkout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
		sessionContainer = (SessionContainer) session.getAttribute(Constants.SESSION_CONTAINER_KEY);
		shoppingCart = sessionContainer.getShoppingCart();
		preparedOrder = (Order) session.getAttribute(Constants.PREPARED_ORDER_KEY);
		if(shoppingCart.isEmpty()) {
			return Constants.CART;
		}

		if(null == preparedOrder) {
			preparedOrder = new Order();
		}
		account = sessionContainer.getAccount();
		preparedOrder.setAccount(account);
		preparedOrder.setAccountId(account.getId());
		preparedOrder.setReceiver(account.getTrueName());
		preparedOrder.setMobile(account.getMobile());
		preparedOrder.setShippingAddress(account.getAddress());
		preparedOrder.setZipCode(account.getZipCode());
		preparedOrder.setDeliveryType(Constants.NORMAL_DELIVERY);
		preparedOrder = calculateFreight(preparedOrder, shoppingCart.getTotalPrice());
		session.setAttribute(Constants.PREPARED_ORDER_KEY, preparedOrder);

		return Constants.CHECKOUT;
	}
	
	private Order calculateFreight(Order order, double totalPrice) {
		if(Constants.FAST_DELIVERY.equals(order.getDeliveryType())){
			order.setDeliveryFee(Constants.FAST_DELIVERY_FEE);
		}else if(totalPrice > Constants.FREE_DELIVERY_PRICE){
			order.setDeliveryFee(0);
		}else if(Constants.NORMAL_DELIVERY.equals(order.getDeliveryType())){
			order.setDeliveryFee(Constants.NORMAL_DELIVERY_FEE);
		}else if(Constants.POST_DELIVERY.equals(order.getDeliveryType())){
			order.setDeliveryFee(Constants.POST_DELIVERY_FEE);
		}

        return order;
	}
	
	public String setDeliveryType(){
		if(Constants.NORMAL_DELIVERY.equals(deliveryType) || Constants.FAST_DELIVERY.equals(deliveryType)
				|| Constants.POST_DELIVERY.equals(deliveryType)){
			preparedOrder.setDeliveryType(deliveryType);
			
			Integer totalPrice = shoppingCart.getTotalPrice();
			calculateFreight(preparedOrder, shoppingCart.getTotalPrice());
			
			freight = Integer.toString(preparedOrder.getDeliveryFee());
			total = Integer.toString(totalPrice + preparedOrder.getDeliveryFee());
		}
		return Constants.SET_DELIVERY_TYPE;
	}
	
}
